<template>
  <div class="layout-warpper content">
    <div class="layout-header content-header">
      <!--
        label-width="80px" -->
      <el-form ref="formSearch" :model="formSearch" :rules="rules" :inline="true" class="form-search" size="normal">
<!--        <el-form-item label="行业类别">
          <el-cascader
            v-model="formSearch.xmlx"
            option-max-width="100px"
            class="ui-w240"
            :props="{ multiple: true }"
            collapse-tags
            :collapse-tags-max-num="1"
            :tooltip-max-width="200"
            tooltip-effect="light"
            :options="TASKOBJ.industryTypeAndIndustry"
            @change="industryTypeAndIndustryFn"
          />
        </el-form-item>-->

        <el-form-item label="交易方式">
          <el-select
            v-model="formSearch.cgfs"
            class="ui-w120"
            option-max-width="180px"
            placeholder="请选择"
            clearable
            @change="handleSearchFn()"
          >
            <!-- <el-option key label="全部" value></el-option> -->
            <el-option v-for="(value, key) in cgfsType" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="资审方式">
          <el-select
            v-model="formSearch.scfs"
            class="ui-w120"
            option-max-width="180px"
            placeholder="请选择"
            clearable
            @change="handleSearchFn()"
          >
            &lt;!&ndash; <el-option key label="全部" value></el-option> &ndash;&gt;
            <el-option v-for="(value, key) in scfsType" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>-->
        <el-form-item label="开标时间" prop="date">
          <el-date-picker
            v-model="formSearch.date"
            :clearable="true"
            type="daterange"
            align="right"
            style="width: 240px"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="handleSearchFn"
          />
        </el-form-item>
        <el-form-item label="" prop="keyWord">
          <!-- clearable -->
          <el-input
            v-model.trim="formSearch.keyword"
            style="background: #1890ff"
            placeholder="项目/标段/名称/编号"
            class="ui-w320"
            @keydown="submitSearchFn"
          >
            <el-button slot="append" type="primary" icon="el-icon-search" @click="submitSearchFn" />
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="layout-body">
      <el-table ref="taskTable" v-loading="tableLoading" :data="tableData" height="100%" stripe>
        <el-table-column type="index" align="left" label="序号" width="50">
          <template slot-scope="scope">
            {{ pageObj.currentPage * pageObj.pageSize + 1 + scope.$index }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="标段名称" show-overflow-tooltip/>
        <el-table-column prop="code" label="标段编号" show-overflow-tooltip/>
        <el-table-column prop="xmname" label="项目名称" show-overflow-tooltip/>
<!--        <el-table-column prop="xmlx" label="行业类别" min-width="115" />-->
        <el-table-column prop="xm.cgfs" label="招标方式" :formatter="formatterCgfsType"/>
<!--        <el-table-column prop="xm.scfs" label="资审方式" :formatter="formatterScfsType"/>-->
        <el-table-column prop="xm.kbtime" label="开标时间" min-width="112" max-width="150"/>
        <el-table-column prop="kbroom" label="开标室" min-width="115" />
        <el-table-column prop="pbroom" label="评标室" min-width="115" />
        <el-table-column prop="pbroom" label="见证阶段" min-width="115" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.taskList" :key="index">
              {{ item.taskname }}<span v-if="index < scope.row.taskList.length-1">,</span>
            </span>
          </template>
        </el-table-column>
<!--        <el-table-column prop="taskList[0].jzstarttime" label="见证开始时间" min-width="115" />-->
<!--        <el-table-column prop="taskList[0].jzendtime" label="见证结束时间" min-width="115" />-->
<!--        <el-table-column prop="pbroom" label="任务来源" min-width="115" />-->
        <el-table-column label="操作" align="left" header-align="center" width="150">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="default"
              @click="downloadAttachFn(scope.row)">见证日志</el-button>
            <el-button
              v-if="scope.taskstatus !== 'YWC'"
              type="text"
              size="default"
              @click="enterClickFn(scope.row)">进入见证</el-button>
<!--            <el-button
              type="text"
              size="default"
              @click="enterClickFn(scope.row)">进入见证</el-button>-->
<!--            <el-button
              v-if="witnessStage === 'witnessing'"
              type="text"
              size="default"
              @click="enterClickFn(scope.row)">进入见证</el-button>
            <el-button
              v-if="witnessStage === 'toWitness'"
              type="text"
              size="default"
              @click="startClickFn(scope)">开始见证</el-button>
            <el-button type="text" size="default" @click="allocateUserClickFn(scope, props)">
              移交见证
            </el-button>
            <el-button
              v-if="witnessStage === 'witnessing'"
              type="text"
              size="default"
              @click="finishWitnessFn(scope, props)">结束见证</el-button>
            <el-button
              v-if="witnessStage === 'witnessing'"
              type="text"
              size="default"
              @click="finishWitnessFn(scope, props)">见证时间</el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->

    <div class="layout-footer ui-pt5">
      <!-- {{ pageObj.total + " " + pageObj.pageSize }} -->
      <wpagination
        v-if="pageObj.total > pageObj.pageSizes[0]"
        :total="pageObj.total"
        :page.sync="pageObj.currentPage"
        :limit.sync="pageObj.pageSize"
        :pageSizes="pageObj.pageSizes"
        @pagination="subtaskListFn"
      />
    </div>
  </div>
</template>
<script>
import _ from "lodash";
import { page } from "../../../../api/weeon/myWitness";
// taskList,subtaskList,
import { moduleInit, taskCancel, myWitnessList } from "../../../../api/api.js";
// import TopStatus from "../../../../components/TopStatus.vue";
// import AssignDialog from "../../../../components/dialog/AssignDialog.vue";
// import WitnessRecord from "../../../../components/dialog/WitnessRecord.vue";
// import TaskTable from "./TaskTable";

import SIdentify from "../../../../components/sidentify.vue";
import { list } from "@/api/weeon/room";
export default {
  components: {
    SIdentify,
    // WitnessRecord,
    // TaskTable
  },
  data() {
    // 验证码校验
    var validateCode = (rule, value, callback) => {
      if (value === "" || value === undefined) {
        callback(new Error("验证码不能为空"));
      } else if (value !== this.identifyCode) {
        callback(new Error("验证码不正确"));
      } else {
        callback();
      }
    };
    return {
      tableLoading: false,
      pageObj: {
        total: 0,
        currentPage: 0,
        pageSize: 10,
        pageSizes: [10, 20, 30]
      },
      formSearch: {
        // date: [this.$moment(new Date()).format("yyyy-MM-DD"), this.$moment(new Date()).format("yyyy-MM-DD")],
        date: [],
        keyword: "",
        xmlx: "",
        cgfs: "",
        scfs: ""
      },
      scfsType: {"1":"资格预审", "2":"资格后审"},
      cgfsType: {"1":"公开招标", "2":"邀请招标"},


      multipleTaskSelection: [],
      multipleSubTaskSelection: [],
      activeName: "expertList",
      TASKOBJ: {},
      tenderModeData: [],
      industryTypeArr: [],
      liveStatusArr: [],
      roomNameList: [],

      rules: {
        // date: [{ required: true, message: "日期不能为空", trigger: "blur" }],
        // keyWord: [{ required: true, message: "key不能为空", trigger: "blur" }],
      },
      currentWitness: {},
      identifyCode: "",
      cancelLoading: false,
      cancelVisible: false,
      cancelForm: {},
      cancelRules: {
        // reason: [
        //   { required: true, message: "停止原因不能为空", trigger: "blur" },
        // ],
        code: [
          {
            validator: validateCode,
            trigger: "blur"
          },

          { required: true, message: "验证码不能为空", trigger: "change" }
        ]
      },
      tableTaskList: [],
      tableData: [],
      recordShow: false,
      subtaskRow: {},
      recordData: [],
      recordType: "random",
      assignShow: false,
      assignData: [],
      assignType: "random",
      pageSizes: [10, 20, 30],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      }
    };
  },
  created() {
    this.subtaskListFn();
    // await this.handleSearchFn();
  },
  methods: {
    //格式化交易方式
    formatterCgfsType(row, col, val){
      console.log(val);
      let str = "";
      if (val) {
        str = this.cgfsType[val];
      }
      return str;
    },
    //格式化交易方式
    formatterScfsType(row, col, val){
      console.log(val);
      let str = "";
      if (val) {
        str = this.scfsType[val];
      }
      return str;
    },
    // 验证码开始
    refreshCode() {
      this.identifyCode = this.makeCode("1234567890", 4);
    },
    makeCode(o = "1234567890", l) {
      let code = "";
      for (let i = 0; i < l; i++) {
        code += o[this.randomNum(0, o.length)];
      }
      return code;
    },
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    // 验证码结束
    // 主任务表格多选
    handleTaskSelectionChangeFn(val) {
      this.multipleTaskSelection = val;
      console.log("val", val);
      // this.assignData = val;
    },
    // 子任务表格多选
    handleSubTaskSelectionChangeFn(val) {
      console.log("val", val);
      this.multipleSubTaskSelection = val;
      this.assignData = val;
    },
    // table 展开收起
    expandChangeFn(row) {
      console.log("row", row);
      if (!row.children) {
        let o = {
          witnessTaskId: row.witnessTaskId
        };
        let index = "";
        this.tableData.some((item, i) => {
          if (item.witnessTaskId === row.witnessTaskId) {
            index = i;
            return;
          }
        });
        console.log("index", index);

        this.subtaskListFn(o, index);
      }
    },
    // 取消见证-提交
    cancelSubmitFn() {
      this.$refs["cancelForm"].validate((valid) => {
        if (valid) {
          if (this.cancelForm.code == this.identifyCode) {
            this.cancelLoading = true;
            console.log("111");
            this.taskCancelFn();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 取消见证-提交
    cancelCloseFn() {
      this.cancelVisible = false;
    },
    // 取消见证接口 ---接口需要改动 by link 20211110
    async taskCancelFn() {
      try {
        let p = {
          witnessSubTaskId: this.currentWitness.witnessSubTaskId
        };
        const res = await taskCancel(p);
        if (res.success) {
          this.cancelVisible = false;
          this.cancelLoading = false;
          this.$message({
            type: "success",
            message: res.message || "操作成功",
            single: true
          });
        } else {
          this.$message({
            type: "error",
            message: res.message || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (err) {
        console.error(err);
        this.$message({
          type: "error",
          message: "获取数据失败，请稍后再试",
          single: true
        });
      }
    },
    // 行业类型转文字
    industryFn(val) {
      let array = this.TASKOBJ.industryTypeAndIndustry;

      let obj = this.findArrayFn(array, val) || {};
      return obj.label;
    },
    randomAssignFn() {
      this.assignType = "random";
    },
    orientationAssignFn() {
      this.assignShow = true;
      this.assignType = "orientation";
      // this.assignData = [];
    },
    batchApproveFn() {},
    assignSubmitFn() {},
    assignCloseFn() {
      this.assignShow = false;
    },
    recordSubmitFn() {},
    recordCloseFn() {
      this.recordShow = false;
    },
    indexFn(index) {
      return index + 1 + (this.pageObj.currentPage - 1) * this.pageObj.pageSize;
    },
    downloadAttachFn(row) {
      debugger
      const downloadUrl = `${process.env.VUE_APP_API}/witness/weeon/buss/task/jzr/jzrz_download?bdguid=`+row.guid
      const downloadRes = async () => {
        let response = await fetch(downloadUrl); // 内容转变成blob地址
        let blob = await response.blob(); // 创建隐藏的可下载链接
        let objectUrl = window.URL.createObjectURL(blob);
        let a = document.createElement("a");
        a.href = objectUrl;
        a.download = `见证日志.pdf`;
        a.click();
        a.remove();
      };
      downloadRes();
    },
    async subtaskListFn() {
      try {
        this.tableLoading = true;
        this.tableData = [];
        let params = {
          taskstatus :"YWC",
          xmlx: this.formSearch.xmlx,
          cgfs: this.formSearch.cgfs,
          scfs: this.formSearch.scfs,
          keyword: this.formSearch.keyword,
          pageNo: this.pageObj.currentPage,
          pageSize: this.pageObj.pageSize
        };
        if (this.formSearch.date && this.formSearch.date.length) {
          params.beginkbtime = this.formSearch.date[0] + " 00:00:00"; // 起始时间
          params.endkbtime = this.formSearch.date[1] + " 23:59:59"; //
        }
        const res = await page(params);
        this.tableLoading = false;
        if (res.stat === 1) {
          if (res.data.totalElements === 0 && this.pageObj.currentPage !== 0) {
            this.pageObj.currentPage = 0;
            this.$nextTick(() => {
              this.subtaskListFn();
            });
            return;
          }
          this.tableData = res.data.content;
          console.log("1111122"+res.data.content);
          this.pageObj.total = res.data.totalElements;
        } else {
          this.$message({
            type: "error",
            message: res.msg || "获取数据失败，请稍后再试",
            single: true
          });
        }
      } catch (error) {
        console.log(error);
        this.tableLoading = false;
      }
    },
    handleSearchFn() {
      this.pageObj.total = 0;
      this.pageObj.currentPage = 0;
      this.subtaskListFn();
      // await this.taskListFn();
    },
    // 管理员任务列表 /gtv/witness/subtask/list
    // async subtaskListFn() {
    //   // currentPage // 当前页数
    //   // endTime // 结束时间
    //   // industry // 枚举值: QT
    //   // industryType // 枚举值: GCJS,ZFCG,CQJY,TDJY,YPCG
    //   // pageSize  // 每页条数
    //   // search // 关键字搜索
    //   // startTime // 起始时间
    //   // tenderMode // 枚举值: PUBLIC_BIDDING,INVITE_BIDDING
    //   // witnessSubTaskStatus // 枚举值: UNASSIGNED,ASSIGNED,WITNESSING,WITNESS_FINISHED,WITNESS_UN_REVIEWED,WITNESS_PASS
    //   try {
    //     let obj = {};
    //     let industryList = [];
    //     let industryTypeList = [];
    //     this.formSearch.industry.forEach((item) => {
    //       if (!obj[item[0]]) {
    //         obj[item[0]] = 1;
    //         if (item[0] != null) {
    //           industryTypeList.push(item[0]);
    //         }
    //       }
    //       if (item[1] != null) {
    //         industryList.push(item[1]);
    //       }
    //     });
    //     let tenderModeList = this.formSearch.tenderMode;
    //     let p = {
    //       pageNum: this.pageObj.currentPage, // 当前页数
    //       pageSize: this.pageObj.pageSize, // 每页条数
    //       witnessStatus: "ING_WITNESS",
    //       tenderModeList, // 交易方式
    //       industryList, // 行业类型
    //       industryTypeList, // 行业类型
    //       qualificationExamMethod: this.formSearch.status[0], // 资审方式
    //       search: this.formSearch.keyWord // 搜索
    //     };
    //     // console.log("this.formSearch.date", this.formSearch.date);
    //
    //     if (this.formSearch.date && this.formSearch.date.length) {
    //       p.startDate = this.formSearch.date[0] + " 00:00:00"; // 起始时间
    //       p.endDate = this.formSearch.date[1] + " 23:59:59"; //
    //     }
    //     this.tableTaskList = [];
    //     this.pageObj.total = 0;
    //     const res = await myWitnessList(p);
    //     if (res.success) {
    //       if (res.data.data.length == 0 && this.pageObj.currentPage != 1) {
    //         this.pageObj.currentPage = 1;
    //         this.$nextTick(() => {
    //           this.subtaskListFn();
    //         });
    //         return;
    //       }
    //       this.tableTaskList = this.transferList(res.data.data);
    //       this.pageObj.total = res.data.pageBean.count;
    //     } else {
    //       this.$message({
    //         type: "error",
    //         message: "获取数据失败，请稍后再试",
    //         single: true
    //       });
    //     }
    //   } catch (err) {
    //     console.error(err);
    //     this.$message({
    //       type: "error",
    //       message: "获取数据失败，请稍后再试",
    //       single: true
    //     });
    //   }
    // },

    roomIdchangeFn() {
      this.handleSearchFn();
    },
    typeChangeFn() {
      this.handleSearchFn();
    },
    statusChangeFn() {
      this.handleSearchFn();
    },
    recordClickFn({ row }) {
      console.log("row", row);

      this.subtaskRow = row;
      this.recordShow = true;
    },
    updateClickFn() {},
    //进入见证
    enterClickFn(row) {
      if (!row.taskList[0].taskcode) {
        this.$message({
          type: "error",
          message: "见证阶段不存在",
          single: true
        });
        return;
      }
      let code = row.taskList[0].taskcode.toLowerCase();
      this.$router.push({ path: '/witnessStage/'+code+'Stage', query: { bdid: row.id }});
    },
    cancelWitnessFn({ row }) {
      this.cancelVisible = true;
      this.currentWitness = row;
      console.log("row", row);

      this.refreshCode();
    },
    detailClickFn() {},
    showPdfWitnessFn() {},
    industryTypeAndIndustryFn(val) {
      let obj = {};
      this.TASKOBJ.industryTypeAndTenderMode.forEach((item) => {
        if (item.children) {
          obj[item.value] = item.children.map((item) => {
            return {
              label: item.label,
              value: item.value
            };
          });
        }
      });
      let o2 = {};
      this.tenderModeData = [];
      if (!val.length) {
        for (let key in obj) {
          this.tenderModeData = this.tenderModeData.concat(obj[key]);
        }
      } else {
        val.forEach((item) => {
          if (obj[item[0]] && !o2[item[0]]) {
            o2[item[0]] = 1;
            this.tenderModeData = this.tenderModeData.concat(obj[item[0]]);
          }
        });
      }
      this.tenderModeData = _.uniqWith(this.tenderModeData, _.isEqual);
      this.submitSearchFn();
    },
    submitSearchFn() {
      this.pageObj.total = 0;
      this.pageObj.currentPage = 0;
      this.handleSearchFn();
    },
    // 将后端传递的数据结构进行转化
    transferList(list) {
      for (let item of list) {
        let count = 0;
        const bidListLength = item.bidsectionInfoList.length;
        item["bidsectionInfoListCopy"] = [];
        for (let j = 0; j < bidListLength; j++) {
          const length = item.bidsectionInfoList[j].operData.result.length;
          const operData = item.bidsectionInfoList[j].operData;
          for (let i = 0; i < length; i++) {
            let obj = {};
            for (let key in item["bidsectionInfoList"][j]) {
              obj[key] = item["bidsectionInfoList"][j][key];
              delete obj["operData"];
            }
            obj = { ...obj, ...operData["result"][i]["data"], pageOpers: operData["result"][i]["pageOpers"] };
            item["bidsectionInfoListCopy"][count] = obj;
            count++;
          }
        }
        item["bidsectionInfoList"] = item["bidsectionInfoListCopy"];
        delete item["bidsectionInfoListCopy"];
      }
      return list;
    }
  }
};
</script>
<style lang="scss" scoped>
.content {
  width: 100%;
  height: 100%;
  //采用flex布局，代替calc属性 by link 20211020
  display: flex;
  flex-flow: column;
}
.content-header {
  margin-top: 10px;
}
.form-search {
  padding-top: 10px;
  padding-left: 20px;
  background: #efefef;
  margin-bottom: 10px;
}
.tag-list {
  padding: 0 10px 10px;
}
.task-status {
  span {
    background: #ccc;
    border-radius: 50%;
    display: inline-block;
    margin-right: 4px;
    width: 24px;
    height: 24px;
    font-size: 14px;
    text-indent: 5px;
    line-height: 24px;
    overflow: hidden;
    color: #fff;
  }
  .WITNESSING {
    background: $WITNESSING;
  }
  .WITNESS_FINISHED {
    background: $WITNESS_FINISHED;
  }
  .ASSIGNED {
    background: $ASSIGNED;
  }
  .UNASSIGNED {
    background: $UNASSIGNED;
  }
}
.cancel-dialog {
  .info {
    padding-left: 28px;
    position: relative;
    i {
      position: absolute;
      top: 0;
      left: 0;
      color: #e6ad00;
      font-size: 18px;
      vertical-align: top;
    }
  }
}
</style>
